package com.skz.job.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 宋开宗
 * @create: 2019-02-19 11:45
 * 腾讯位置服务
 **/
public class LocationUtils {
    private static final String url = "https://apis.map.qq.com/ws/geocoder/v1/?location=";
    /**
     * key自己单独申请
     */
    private static final String mapKey = "JLPBZ-2AS6P-VXDDG-VDTKP-O3ZBS-A2BG2";

    /**
     * 逆地址解析
     *
     * @param x
     * @param y
     * @return
     */
    public static Map<String, String> parse(String x, String y) {
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url + x + "," + y + "&key=" + mapKey);
        HttpEntity entity;
        JSONObject result = null;
        try {
            entity = client.execute(get).getEntity();
            result = JSON.parseObject(EntityUtils.toString(entity));
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject addressObject = result.getJSONObject("result").getJSONObject("address_component");
        String district = addressObject.getString("district");
        String city = addressObject.getString("city");
        String province = addressObject.getString("province");
        String code = result.getJSONObject("result").getJSONObject("ad_info").getString("adcode");
        String address = result.getJSONObject("result").getString("address");
        Map<String, String> map = new HashMap<>(5);
        map.put("district", district);
        map.put("city", city);
        map.put("province", province);
        map.put("code", code);
        map.put("address", address);
        return map;
    }
}
